
package com.hulk.ratel.notify.exceptionhandler;



import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;


/**
 * @author hulk
 */


@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(value = ClientAbortException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public void doErrorHandler(HttpServletRequest req, HttpServletResponse resp, ClientAbortException e) throws Exception {
        processException(req, resp, BussErrCode.E_900013.getErrCode(), BussErrCode.E_900013.getErrDesc(), e);
    }



    @ExceptionHandler(value = BaseRteException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public void doErrorHandler(HttpServletRequest req, HttpServletResponse resp, BaseRteException e) throws Exception {
        processException(req, resp, e.getErrorCode(), e.getMessage(), e);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public void doErrorHandler(HttpServletRequest req, HttpServletResponse resp, Exception e) throws Exception {
        processException(req, resp, BussErrCode.E_999999.getErrCode(), BussErrCode.E_999999.getErrDesc(), e);
    }

    private void processException(HttpServletRequest req, HttpServletResponse resp, String errorCode, String errorMsg, Throwable e) throws Exception {

        resp.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        resp.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        resp.setCharacterEncoding(StandardCharsets.UTF_8.name());
        PrintWriter wr = resp.getWriter();
        wr.write("{\"ResponseStatus\":500}");
        wr.flush();
        wr.close();

    }



}
